package com.example.timewidget.widgets

import android.Manifest
import android.app.AlarmManager
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.widget.RemoteViews
import androidx.annotation.RequiresPermission
import com.example.timewidget.MainActivity
import com.example.timewidget.R
import com.example.timewidget.util.TimeUtils

class TimeTextWidgetProvider : AppWidgetProvider() {
    val TAG = "czy"
//    private lateinit var remoteViews: RemoteViews

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray

    ) {    // 启动 Handler 定时更新
        val handler = Handler(Looper.getMainLooper())
        Log.d(TAG, "onUpdate called with ${appWidgetIds.size} widget IDs")
        handler.post(object : Runnable {
            override fun run() {
                appWidgetIds.forEach { appWidgetId ->
                    val remoteViews = RemoteViews(
                        context.packageName,
                        R.layout.time_text_widget_layout
                    )
                    remoteViews.setTextViewText(R.id.tv_clock, TimeUtils.getCurrentTime())
                    val intent = Intent(context, MainActivity::class.java).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                    }
                    val pendingIntent: PendingIntent = PendingIntent.getActivity(
                        /* context = */ context,
                        /* requestCode = */
                        0,
                        /* intent = */
                        intent,
                        /* flags = */
                        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                    )
                    remoteViews.setOnClickPendingIntent(R.id.clock2, pendingIntent)
                    appWidgetManager.updateAppWidget(appWidgetId, remoteViews)
                }
                handler.postDelayed(this, 1000) // 每秒执行一次a
            }

        })
    }

    // 广播接收
    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
//        if (intent.action == ACTION_MANUAL_UPDATE) {
//            Log.d(TAG, "onReceive: 手动触发更新")
//            val appWidgetManager = AppWidgetManager.getInstance(context)
//            val componentName = ComponentName(context, TimeTextWidgetProvider::class.java)
//            val appWidgetIds = appWidgetManager.getAppWidgetIds(componentName)
//            onUpdate(context, appWidgetManager, appWidgetIds)
//
//            // 继续调度下一次更新
////            schedulePeriodicUpdate(context)
//        }
        Log.d(TAG, "onReceive: 动作 = ${intent.action}")
    }

    // 初始化（第一次创建
    override fun onEnabled(context: Context) {
        super.onEnabled(context)
        Log.d(TAG, "onEnabled: 组件首次启用，触发更新")
//        val appWidgetManager = AppWidgetManager.getInstance(context)
//        // 获取所有组件 ID（可能多个实例）
//        val appWidgetIds = appWidgetManager.getAppWidgetIds(
//            ComponentName(context, TimeTextWidgetProvider::class.java)
//        )
//        onUpdate(context, appWidgetManager, appWidgetIds)
    }

}